package com.cs.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cs.constant.AuthConstant;
import com.cs.domain.LoginUser;
import com.cs.domain.SysLoginUser;
import com.cs.mapper.LoginUserMapper;
import com.cs.mapper.SysLoginUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysLoginUserMapper sysLoginUserMapper;

    @Autowired
    private LoginUserMapper loginUserMapper;
    /**
     * 微信小程序的APPID
     */
    @Value("${wx.appid}")
    private String appid;
    /**
     * 微信小程序的APPsecret
     */
    @Value("${wx.appsecret}")
    private String appsecret;
    /**
     * 微信小程序的tokenurl
     */
    @Value("${wx.tokenurl}")
    private String tokenurl;

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 这就是登录系统
     * 前台商城
     * 后台登录
     * 需要通过前端请求头中参数进行区分
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //登陆的标识
        String loginType = request.getHeader(AuthConstant.LOGIN_TYPE);
        if (StringUtils.isEmpty(loginType)) {
            loginType = AuthConstant.SYS_USER;
        }
        switch (loginType) {
            case AuthConstant.SYS_USER:
                SysLoginUser sysLoginUser = sysLoginUserMapper.selectOne(new LambdaQueryWrapper<>(SysLoginUser.class).eq(SysLoginUser::getUsername, username));
                if (!ObjectUtils.isEmpty(sysLoginUser)) {
                    //查询权限
                    List<String> auths = sysLoginUserMapper.findPermsByUserId(sysLoginUser.getUserId());
                    sysLoginUser.setAuths(auths);
                }
                return sysLoginUser;
            case AuthConstant.MEMBER:
                //因为前端是微信小程序，需要APPID，appsecret，tokenurl访问微信接口服务，返回一个openID
                String wxAuthUrl = String.format(tokenurl, appid, appsecret, username);
                String wxJson = restTemplate.getForObject(wxAuthUrl, String.class);
                //转化为json对象
                JSONObject jsonObject = JSON.parseObject(wxJson);
                String openid = jsonObject.get("openid").toString();
                if (StringUtils.hasText(openid)) {
                    //判断数据库中是否有这个数据
                    LoginUser loginUser = loginUserMapper.selectById(openid);
                    if(ObjectUtils.isEmpty(loginUser)){
                        loginUser=createLoginUser(openid);
                    }
                    return loginUser;
                }
        }
        return null;
    }

    /**
     * 创建一个前台用户
     * @return
     */
    private LoginUser createLoginUser(String openId) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(openId);
        loginUser.setModifyTime(new Date());
        loginUser.setStatus(1);
        loginUser.setScore(0);
        loginUser.setUserRegtime(new Date());
        //获得ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteHost();
        loginUser.setUserRegip(ip);
        loginUser.setUserLastip(ip);
        return loginUser;
    };
}
